package com.cn.wkditui;

import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;


import com.cn.wkditui.bean.MarkerInfo;

/**
 * Created by Administrator on 2016/4/20.
 */
public class MapListActivity extends BaseActivity {
    private static final String TAG = "MainList";
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.ll)
    LinearLayout llb;
    public MyLocationListenner myListener = new MyLocationListenner();
    private List<MarkerInfo> beans;
    private BaiduMap mBaiduMap;
    private AQuery aq;
    private boolean isFirstLoc =true;
    private double currentLat,currentLng;
    private LocationClient mLocClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivity_maplist);
        ButterKnife.bind(this);

        init();
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        //Log.e(TAG, "onCreate() returned: ===================================== ");
//        MarkerInfo m = new MarkerInfo();
////        43.8922810000,125.3663330000
//        m.setLat(43.8922810000 + "");
//        m.setLng(125.3663330000 + "");
//        m.setId(1 + "");
//        m.setShortName("姓名");
//
//        MarkerInfo m1 = new MarkerInfo();
////        43.8922810000,125.3663330000
//        m1.setLat(43.8922810000 + "");
//        m1.setLng(125.3666430000 + "");
//        m1.setId(1 + "");
//        m1.setShortName("姓名");
//
//        beans.add(m);
//        beans.add(m1);
//        addInfosOverlay(beans);


        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                //获得marker中的数据
                MarkerInfo info = (MarkerInfo) marker.getExtraInfo().get("info");

                InfoWindow mInfoWindow;
                //生成一个TextView用户在地图中显示InfoWindow
                TextView location = new TextView(getApplicationContext());
                location.setBackgroundResource(R.mipmap.background);
                location.setPadding(20, 20, 20, 20);
                String text = "";
                if(info.getStatus().equals("-1")||info.getStatus().equals("-2")){
                    if(info.getStatus().equals("-1")){
                        text =info.getName()+"    状态:"+"调查问卷不配合";
                    }else if(info.getStatus().equals("-2")){
                        text =info.getName()+"    状态:"+"联系方式不配合";
                    }


                }else if(info.getStatus().equals("1")){
                    //Log.e("list","map = mark1");
                    text =info.getName()+"    状态:"+"已完毕且注册";
                }else if(info.getStatus().equals("2")){
                    text =info.getName()+"    状态:"+"已完毕未注册";
                }else{
                    text =info.getName()+"    状态:"+"数据不对";
//                    icon = BitmapDescriptorFactory.fromResource(R.mipmap.mark_1);
                }
                location.setText(text);
                //将marker所在的经纬度的信息转化成屏幕上的坐标
                final LatLng ll = marker.getPosition();
                Point p = mBaiduMap.getProjection().toScreenLocation(ll);
                //Log.e(TAG, "--!" + p.x + " , " + p.y);
                p.y -= 47;
                LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
                //为弹出的InfoWindow添加点击事件
//                mInfoWindow = new InfoWindow(location, llInfo,
//                        new InfoWindow.OnInfoWindowClickListener() {
//
//                            @Override
//                            public void onInfoWindowClick() {
//                                //隐藏InfoWindow
//                                mBaiduMap.hideInfoWindow();
//                            }
//                        });

//                BitmapDescriptor b = new BitmapDescriptor()

                LatLng latlng = new LatLng(Double.parseDouble(info.getLat()), Double.parseDouble(info.getLng()));
                BitmapDescriptor v = BitmapDescriptorFactory.fromView(location);
//                BitmapFactory.decodeResource(getResources(), R.mipmap.camera));
//                );
                mInfoWindow = new InfoWindow(v, llInfo, 1, new InfoWindow.OnInfoWindowClickListener() {
                    @Override
                    public void onInfoWindowClick() {
                        mBaiduMap.hideInfoWindow();
                    }
                });

                //显示InfoWindow
                mBaiduMap.showInfoWindow(mInfoWindow);
                //设置详细信息布局为可见
                llb.setVisibility(View.VISIBLE);
                //根据商家信息为详细信息布局设置信息
                popupInfo(llb, info);
                return true;
            }
        });
    }

    private void init() {
        beans = new ArrayList<>();

        aq = new AQuery(this);

        mBaiduMap = mapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        //		option.setLocationMode(LocationMode.Hight_Accuracy);
        option.setOpenGps(true);// 打开gps
        //		option.setPriority(LocationClientOption.GpsFirst);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(10000);
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    public class MyLocationListenner implements BDLocationListener {


        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }
            if(location.getLatitude()==4.9e-324){
                Toast.makeText(MapListActivity.this, "定位失败", 0).show();
                return ;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            System.out.println("location=============="+location.getLatitude()+location.getLongitude());
            if (isFirstLoc) {


                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 17);
                mBaiduMap.animateMapStatus(u);
                currentLng = location.getLongitude();
                currentLat =location.getLatitude();
                load();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
    private void load() {
        RequestParams params = new RequestParams();
//        params.addBodyParameter("phone", MyPreference.getInstance(this).getStaffid());
//        params.addBodyParameter("phone", "13154393934");
        params.addBodyParameter("lat", currentLat+"");
        params.addBodyParameter("lng", currentLng+"");

        Log.e("map", "lat==============="+currentLat);
        Log.e("map", "lng==============="+currentLng);
        new HttpUtils().send(HttpRequest.HttpMethod.POST, Consts.HOST + Consts.GETLIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    Log.e("re", responseInfo.result);
                    JSONObject json = new JSONObject(responseInfo.result);
                    for (int i = 0; i < json.getJSONArray("data").length(); i++) {
                        MarkerInfo info = new MarkerInfo();
                        info.setId(json.getJSONArray("data").getJSONObject(i).getString("id"));
                        info.setLat(json.getJSONArray("data").getJSONObject(i).getString("lat"));
                        info.setLng(json.getJSONArray("data").getJSONObject(i).getString("lng"));
                        info.setStatus(json.getJSONArray("data").getJSONObject(i).getString("status"));
                        info.setName(json.getJSONArray("data").getJSONObject(i).getString("name"));
                        info.setPhoto(json.getJSONArray("data").getJSONObject(i).getString("photo"));
                        info.setCity(json.getJSONArray("data").getJSONObject(i).getString("city"));
                        info.setContacts(json.getJSONArray("data").getJSONObject(i).getString("contacts"));
                        info.setProvince(json.getJSONArray("data").getJSONObject(i).getString("province"));
                        info.setRegionNum(json.getJSONArray("data").getJSONObject(i).getString("regionNum"));
                        beans.add(info);
                    }
                    //Log.e("list","长度"+beans.size());
                    addInfosOverlay(beans);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                //Log.e(TAG, s);
            }
        });
    }

    protected void popupInfo(LinearLayout mMarkerLy, MarkerInfo info) {
        ViewHolder viewHolder = null;
        if (mMarkerLy.getTag() == null) {
            viewHolder = new ViewHolder();
            viewHolder.infoImg = (ImageView) mMarkerLy
                    .findViewById(R.id.iv);
            viewHolder.infoName = (TextView) mMarkerLy
                    .findViewById(R.id.tv_name);
//            viewHolder.infoDistance = (TextView) mMarkerLy
//                    .findViewById(R.id.info_distance);
//            viewHolder.infoZan = (TextView) mMarkerLy
//                    .findViewById(R.id.info_zan);

            mMarkerLy.setTag(viewHolder);
        }
        viewHolder = (ViewHolder) mMarkerLy.getTag();
//        viewHolder.infoImg.setImageResource(info.getId());
        aq.id(viewHolder.infoImg).image(Consts.IMGPATH+info.getPhoto(),false,true);


        //Log.e("View","图片:"+Consts.IMGPATH+info.getPhoto()+"名字:"+info.getId());

        viewHolder.infoName.setText( info.getRegionNum());

//        viewHolder.infoName.setText(info.getName());
//        viewHolder.infoZan.setText(info.getZan() + "");
    }


    public void addInfosOverlay(List<MarkerInfo> infos) {
        mBaiduMap.clear();
        LatLng latLng = null;
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        for (MarkerInfo info : infos) {
            // 位置
            latLng = new LatLng(Double.parseDouble(info.getLat()), Double.parseDouble(info.getLng()));
//            //Log.e("add", "lat===" + latLng.latitude);
//            //Log.e("add", "lat===" + latLng.longitude);
            // 图标
            BitmapDescriptor icon = null;
            if(info.getStatus().equals("-1")||info.getStatus().equals("-2")){
                 icon = BitmapDescriptorFactory.fromResource(R.mipmap.mark_1);
                if(info.getStatus().equals("-1")){
                }else if(info.getStatus().equals("-2")){
                }
            }else if(info.getStatus().equals("1")){
                //Log.e("list","map = mark1");
                icon = BitmapDescriptorFactory.fromResource(R.mipmap.mark1);
            }else if(info.getStatus().equals("2")){
                icon = BitmapDescriptorFactory.fromResource(R.mipmap.mark2);
            }else{
                icon = BitmapDescriptorFactory.fromResource(R.mipmap.mark_1);
            }
            overlayOptions = new MarkerOptions().position(latLng)
                    .icon(icon).zIndex(5);
            marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", info);
            marker.setExtraInfo(bundle);
        }
        // 将地图移到到最后一个经纬度位置
//        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
//        mBaiduMap.setMapStatus(u);
    }

    private class ViewHolder {
        ImageView infoImg;
        TextView infoName;
    }

}
